<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.util.Date"%>
<%@page import="weaver.conn.RecordSet"%>
<%@page import="com.alibaba.fastjson.JSONObject"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="com.zlgs.cqyf.vote.ConnectionUtil"%>
<%@ page import="java.io.PrintWriter" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="weaver.hrm.User" %>
<%@ page import="weaver.hrm.HrmUserVarify" %>
<%
	response.setCharacterEncoding("UTF-8");
	response.setContentType("application/json; charset=utf-8");
	JSONObject retObject = new JSONObject();
	retObject.put("code", 200);
	retObject.put("msg", "操作成功");

	
	try{
		 // 查询数据
	    	String sql = "";
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Object requestType = request.getParameter("requestType");
			String userId = "";
			if(null != requestType && !"".equals(requestType.toString())&&"mobile".equals(requestType.toString())){
				Object userIdObj = request.getParameter("userId");
				if(null == userIdObj || "".equals(userIdObj.toString())){
					throw  new RuntimeException("请求用户Id为空!");
				}
				userId = userIdObj.toString();
				sql = "select top 1    *  from HrmResource where   loginid = N'"+userId+"' ORDER BY ID DESC";
				RecordSet  set0 = new RecordSet();
			    set0.executeSql(sql);
			    if(!set0.next()){
			    	throw  new RuntimeException("请求用户信息异常!");
			    } 
			    
			}else{
				if (!ConnectionUtil.is_local){
					User user = HrmUserVarify.getUser (request , response) ;
					if (null == user)  throw new RuntimeException("请重新登录");
					userId = user.getLoginid();
				}
				
			 }
    	// 获取用户信息

	    // URL 参数
	    Integer awardsParticipatorId  = Integer.parseInt(request.getParameter("awardsParticipatorId"));  // 名单Id
	
	   
	
	    // 1.查询奖项id、二级id
	    sql = "SELECT a.* FROM vote_awards_participator a  where a.id="+awardsParticipatorId;
		RecordSet set = new RecordSet();
	  	set.executeSql(sql);
	    String awardsId ="" ;
	    String awardsSubnameId="" ;
	    while(set.next()){
	        awardsId  = set.getString("awards_id");
	        awardsSubnameId  = set.getString("awards_subname_id");
	    }
	
	    // 2.查询投票配置
	    sql = "SELECT * FROM vote_awards  where id="+awardsId;
	    RecordSet set2 = new RecordSet();
	  	set2.executeSql(sql);
	    int votes = 0;
	    int votesSame = 0;
	    boolean active = false;                     // 活动是否正在进行
	    while(set2.next()){
			
	       String votestr    =  set2.getString("votes");           // 已配置每人票数
	       if(null!=votestr && !"".equals(votestr)){
	    	   try{
		    	   votes = Integer.parseInt(votestr);
	    	   }catch(Exception e){}
	       }
	       String votesSameStr  = 	 set2.getString("votes_same");  // 已配置同一个人可重复次数
	       if(null!=votesSameStr && !"".equals(votesSameStr)){
	    	   try{
	    		   votesSame = Integer.parseInt(votesSameStr);
	    	   }catch(Exception e){}
	       }
	       Long startTime = 0L;
	       String startTimeStr  = set2.getString("start_time");
	       if(null!=startTimeStr && !"".equals(startTimeStr)){
	    	   try{
	    		   startTime = sdf.parse(startTimeStr).getTime();
	    	   }catch(Exception e){}
	       }
	       
	       Long endTime = 0L;
	       String endTimeStr  = set2.getString("end_time");
	       if(null!=endTime && !"".equals(endTime)){
	    	   try{
	    		   endTime = sdf.parse(endTimeStr).getTime();  
	    	   }catch(Exception e){}
	       }
	       
	
	        // 2.1查询本次投票子奖项的状态是否结束
	        sql = "select * from vote_awards_subname where id="+awardsSubnameId;
	        RecordSet set3 = new RecordSet();
		  	set3.executeSql(sql);
	        while(set3.next()){
	            if (set3.getInt("status")==1) active = true;
	        }
	        // 2.2 子奖项未结束是，校验活动时间是否结束
	        if (active){
	            active = startTime<endTime;
	        }
	    }
	    // 活动进行中
	    String reslut = "操作成功";
	    if (active){
	        // 3.查询当前投票记录
	        sql = "select * from vote_awards_ballot where awards_id="+awardsId+" and user_id= N'"+userId+"'";
	        RecordSet set4 = new RecordSet();
		  	set4.executeSql(sql);
			int allowance = votes; // 剩余
	        while (set4.next()){
				allowance -- ;
			}
	        int times = 0;                      // 投票次数
	        while(set4.next()){
	            if (awardsParticipatorId == set.getInt("awards_participator_id")) times++;
	        }
	        
		 
	        // 4.插入数据(未投过或投票次数小于投票限制【同人】，且有余票的情况)
	        if (allowance>0 && votesSame>times){
	            sql = "INSERT INTO vote_awards_ballot(awards_id,awards_participator_id,user_id,create_time) values ("+awardsId+","+awardsParticipatorId+",N'"+userId+"',GETDATE())";
	            RecordSet set5 = new RecordSet();
			  	set5.executeSql(sql);
	            sql = "update vote_awards_participator set votes_num =(votes_num+1)  where id="+awardsParticipatorId;
	            RecordSet set6 = new RecordSet();
			  	set6.executeSql(sql);
	        }
	    }else {
	        reslut = "活动已结束";
	    }
	    retObject.put("msg", reslut);
   
    } catch (Exception e) {
        e.printStackTrace();
        retObject.put("code", -1);
        retObject.put("msg", e.getMessage());
    } finally {
		PrintWriter printWriter =   response.getWriter();
		printWriter.append(retObject.toJSONString());
        if (printWriter != null) printWriter.close();
    }
%>
